const router = require('koa-router')();
const { resBody, md5 } = require("../../utils")
const { models, sequelize } = require('../../utils/db');
const { Decrypt, Encrypt } = require('../../utils/secret');
const { nanoid } = require('nanoid');
const moment = require('moment');

// 绑定激活码
router.post('/code', async (ctx, next) => {
    const { activeCode, deviceInfo, deviceID } = ctx.request.body;
    if (!activeCode || !deviceInfo || !deviceID) {
        throw (resBody.paramError)
    }
    const devInfo = Decrypt(deviceInfo);
    const result = await models.activation_model.findOne({
        where: { activeCode }
    });
    if (!result || !result.id || result.activeState !== 1) {
        throw ({
            code: 501,
            msg: '激活码无效'
        })
    }
    const deviceCode = devInfo.split('IMEI:').pop();
    const expiresTimeArr = result.effecTime.split(',');
    const activeTime = moment().format();
    const expiresTime = moment(activeTime).add(Number(expiresTimeArr[0]), expiresTimeArr[1]).format();
    const updateParams = {
        activeState: 2,
        activeTime,
        expiresTime,
        deviceID,
        deviceInfo: devInfo,
        deviceCode,
        updateTime: activeTime,
    };
    // 更新状态
    try {
        await models.activation_model.update(updateParams, {
            where: {
                id: result.id
            }
        });
        ctx.body = {
            ...resBody.success,
            msg: '激活成功',
        };
    } catch (error) {
        console.log(error);
        ctx.body = {
            ...resBody.failed,
            msg: '激活失败',
        };
    }
});
// 获取激活状态
router.post('/state', async (ctx, next) => {
    const { code } = ctx.request.body;
    if (!code) {
        throw (resBody.paramError)
    }
    try {
        const codeInfo = JSON.parse(Decrypt(code));
        const {deviceCode, activeCode, deviceID} = codeInfo;
        let result = await models.activation_model.findOne({
            where: { activeCode, deviceCode, deviceID  }
        });
        if (!result || !result.id || result.activeState !== 2) {
            throw ({
                code: 501,
                msg: '激活码无效'
            })
        }
        // 距离失效时间毫秒数
        const surplusTime = moment(result.expiresTime).diff(moment());
        const isEffective = surplusTime > 0 ;
        if (!isEffective) {
            await models.activation_model.update({
                activeState: 3,
                updateTime: moment().format(),
            }, {
                where: {
                    activeCode
                }
            });
            result = await models.activation_model.findOne({
                where: { activeCode, deviceCode }
            });
        }
        const resParams = {
            isEffective,
            expiresTime: result.expiresTime,
            activeState: result.activeState,
            deviceCode,
            activeCode,
        };
        const resData = Encrypt(JSON.stringify(resParams));
        ctx.body = {
            ...resBody.success,
            data: resData
        }
    } catch (error) {
        console.log(`获取激活状态: ${error}`);
        throw ({
            ...resBody.failed,
            ...error,
        });
    };
});

module.exports = router